package cn.honglian.org.controller;

import cn.honglian.aop.Log_Aop;
import cn.honglian.basic.anno.PreAuthorize;
import cn.honglian.basic.config.BussinessException;
import cn.honglian.basic.util.AjaxResult;
import cn.honglian.basic.util.PageList;
import cn.honglian.org.domain.Department;
import cn.honglian.org.query.DepartmentQuery;
import cn.honglian.org.service.DepartmentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
@PreAuthorize
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/{id}")
    public Department findById(@PathVariable("id") Long id){
        if (null == id){
           throw new BussinessException("id不能为空");
        }

        return departmentService.findById(id);
    }
    @GetMapping()
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    @PutMapping()
    public AjaxResult addAndUpdate(@RequestBody Department department){

            try {
                if (null!= department.getId()){
                    departmentService.update(department);
                } else {
                    departmentService.add(department);
                }

            }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.me().fail();
            }
        return AjaxResult.me().success();
    }
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
             try {
                 departmentService.delete(id);
             } catch (Exception e){
                 e.printStackTrace();
                 return AjaxResult.me().fail();
             }
             return AjaxResult.me().success();
    }

    @PostMapping()
    @PreAuthorize(name = "部门列表",sn = "/department:list")
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery departmentQuery){

        return departmentService.queryByPage(departmentQuery);

    }

    @PatchMapping()
    public AjaxResult batchDelete(@RequestBody List<Long> ids){

        try {
            departmentService.batchDelete(ids);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
        return AjaxResult.me().success();
    }

    @GetMapping("/tree")
    public List<Department> tree(){

         return  departmentService.getTree();
    }




}
